<template>
  <el-card>
    <!-- 
      lazy 启用数据懒加载
      :load="load" 懒加载时触发的函数
      :tree-props="{            table表格中data数据中对象的字段
        children: 'children',   子节点具体的内容
        hasChildren: 'hasChildren' 代表当前节点有子节点
      }"
      row-key="id" table遍历元素的每个元素的key属性的值
     -->
    <el-table
      :data="categoryList"
      border
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :row-key="getRowKey"
      ref="tableRef"
    >
      <el-table-column label="分类id" prop="id" width="150" />
      <el-table-column label="分类名称" prop="name" />
      <el-table-column width="250" align="center">
        <template #header>
          <el-input
            placeholder="按Enter键添加一级分类"
            v-model="categoryName"
            @keyup.enter="addCategory1"
          />
        </template>
        <template v-slot="{ row }">
          <el-button
            type="primary"
            :icon="Plus"
            size="small"
            title="添加"
            :disabled="row.level === 3"
            @click="showAddCategory(row)"
          />
          <el-button
            type="warning"
            :icon="Edit"
            size="small"
            title="修改"
            @click="showUpdateCategory(row)"
          />
          <el-button type="danger" :icon="Delete" size="small" title="删除" />
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="`${isUpdateCategory ? '更新' : '添加'}${
        category.level === 1 ? '二级' : '三级'
      }分类`"
    >
      <el-form>
        <el-form-item label="分类名称">
          <el-input
            placeholder="请输入分类名称"
            v-model="updatedCategory.name"
            v-if="isUpdateCategory"
          />
          <el-input
            placeholder="请输入分类名称"
            v-model="categoryName"
            v-else
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button
            type="primary"
            @click="updateCategory"
            v-if="isUpdateCategory"
          >
            确定
          </el-button>
          <el-button type="primary" @click="addCategory" v-else>
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XCategory",
};
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  getCategory1ListApi,
  getCategory2ListApi,
  getCategory3ListApi,
  addCategory1Api,
  addCategory2Api,
  addCategory3Api,
  updateCategory1Api,
  updateCategory2Api,
  updateCategory3Api,
} from "@/api/product/category";
import { CategoryList, CategoryItem } from "@/api/product/model/categoryModel";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";

// 添加分类
const categoryName = ref("");
// 添加一级分类
const addCategory1 = async () => {
  if (!categoryName.value) return;
  await addCategory1Api(categoryName.value);
  ElMessage.success("添加一级分类成功");
  getCategory1List();
  categoryName.value = "";
};

const dialogVisible = ref(false);
const category = ref<CategoryItem>({
  id: 0,
  name: "",
});
// 显示添加分类
const showAddCategory = (row: CategoryItem) => {
  isUpdateCategory.value = false;
  dialogVisible.value = true;
  category.value = row;
};

const tableRef = ref();

// 添加二级或三级分类
const addCategory = async () => {
  if (!categoryName.value) return;
  if (category.value.level === 1) {
    // 添加二级分类
    await addCategory2Api(categoryName.value, category.value.id);
  } else if (category.value.level === 2) {
    // 添加三级分类
    await addCategory3Api(categoryName.value, category.value.id);
  }
  // 找到对应的数据，将loaded改成false，代表这个数据没有被加载
  tableRef.value.store.states.treeData.value[
    `${category.value.level}-${category.value.id}`
  ].loaded = false;
  // 重新触发load，加载渲染相应的子节点
  tableRef.value.store.loadOrToggle(category.value);

  ElMessage.success(
    `添加${category.value.level === 1 ? "二级" : "三级"}分类成功`
  );
  cancel();
};

const cancel = () => {
  dialogVisible.value = false;
  categoryName.value = "";
};

const isUpdateCategory = ref(false);
const updatedCategory = ref<CategoryItem>({
  id: 0,
  name: "",
});

// 显示更新分类
const showUpdateCategory = (row: CategoryItem) => {
  isUpdateCategory.value = true;
  dialogVisible.value = true;
  category.value = row;
  updatedCategory.value = {
    ...row,
  };
};

const updateCategory = async () => {
  if (!category.value.name) return;
  if (category.value.level === 1) {
    await updateCategory1Api(category.value.id, category.value.name);
  } else if (category.value.level === 2) {
    await updateCategory2Api(category.value.id, category.value.name);
  } else {
    await updateCategory3Api(category.value.id, category.value.name);
  }
  category.value.name = updatedCategory.value.name;
  ElMessage.success("更新分类成功");
  cancel();
};

const categoryList = ref<CategoryList>([]);

// 一上来获取一级分类列表
const getCategory1List = async () => {
  const res = await getCategory1ListApi();
  categoryList.value = res.map((category) => {
    return {
      ...category,
      hasChildren: true, // 代表该元素具备子节点
      level: 1, // 分类等级
      // children: [],
    };
  });
};
onMounted(getCategory1List);

// 函数的返回值就是table的key值
const getRowKey = (row: CategoryItem) => {
  // 一级分类 1-1 1-2 1-3
  // 二级分类 2-1 2-2 2-3
  // 三级分类 3-1 3-2 3-3
  // 1. 每行元素的key是唯一的（一级、二级和三级分类key不能重复）
  // 2. 更新前后元素key是相同的
  return row.level + "-" + row.id;
};

// 懒加载函数
const load = async (
  row: CategoryItem,
  treeNode: unknown,
  resolve: (data: CategoryList) => void
) => {
  /*
    row 就是点击的当前行元素
    treeNode 点击元素节点
    resolve 一个函数，必须调用，调用就会给当前节点children添加值
      resolve([111, 222])，当前节点的children的值就是[111, 222]
  */
  // 点击触发load函数，加载二级和三级分类
  if (row.level === 1) {
    // 点击一级加载二级分类
    const res = await getCategory2ListApi(row.id);
    resolve(
      res.map((category) => {
        return {
          ...category,
          hasChildren: true,
          level: 2,
        };
      })
    );
  } else if (row.level === 2) {
    // 点击二级加载三级三类
    const res = await getCategory3ListApi(row.id);
    resolve(
      res.map((category) => {
        return {
          ...category,
          level: 3,
        };
      })
    );
  }
};
</script>

<style scoped></style>
